package com.neusoft.oauth2server.config;


import com.neusoft.oauth2server.dto.SecurityUser;
import com.neusoft.oauth2server.dto.UserDTO;

import com.neusoft.oauth2server.entity.Role;
import com.neusoft.oauth2server.entity.Users;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;


@Slf4j
@Service
public class UserService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RestTemplate restTemplate;
    private final static String PROVIDER_URL = "http://192.168.43.231:10001/";

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = restTemplate.getForObject(PROVIDER_URL + "getUserByUsername?username=" + username, Users.class);

        // 查询数据库操作
        //根据用户名查找用户
        if (users == null) {
            throw new UsernameNotFoundException("the user is not found");
        } else {
            SecurityUser securityUser = new SecurityUser(users);
            // 用户角色也应在数据库中获取
            //get roles by username;
            Role[] roles = restTemplate.getForObject(PROVIDER_URL + "getRolesByName?username=" + username, Role[].class);
            List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
            List<Role> roleList = Arrays.asList(roles);
            for (Role role : roleList) {
                authorityList.add(new SimpleGrantedAuthority(role.getRoleName()));
            }
            securityUser.setAuthorities(authorityList);
            return securityUser;
        }
    }
}